<template>
      <el-form ref="ruleForm" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="ruleForm.sex">
            <el-radio label="男" border></el-radio>
            <el-radio label="女" border></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="ruleForm.password"
              type="password"
              autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="校验密码" prop="checkPass">
          <el-input
              v-model="ruleForm.checkPass"
              type="password"
              autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="生日">
          <div class="block">
            <el-date-picker
                v-model="ruleForm.birth"
                type="date"
                placeholder="选择一天"
                :disabled-date="disabledDate"
                :shortcuts="shortcuts"
            >
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="班级">

          <el-select v-model="ruleForm.classId" placeholder="班级">
            <el-option
                v-for="item in classname"
                :key="item.id"
                :label="item.className+'('+item.classNickname+')'"
                :value="item.id"
            >
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="入学日期">
          <div class="block">
            <el-date-picker
                v-model="ruleForm.schoolDate"
                type="date"
                placeholder="选择一天"
                :disabled-date="disabledDate"
                :shortcuts="shortcuts"
            >
            </el-date-picker>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="ins()">确认</el-button>
          <el-button @click="resetForm()">重置</el-button>
        </el-form-item>
      </el-form>


</template>

<script>
import {reactive, toRefs} from 'vue'
import axios from "axios";
import {ref}from 'vue'
import {ElMessage} from "element-plus";
import {findUser, saveUser, upInfo} from "@/utils/api";

export default {
  name: "Stu_re_Form",

  setup() {
    const state = reactive({
      disabledDate(time) {
        return time.getTime() > Date.now()
      },
      shortcuts: [
        {
          text: '今天',
          value: new Date(),
        },
        {
          text: '昨天',
          value: () => {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            return date
          },
        },
        {
          text: '一星期前',
          value: () => {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            return date
          },
        },
      ],
    })

    return {
      ...toRefs(state),
      classname: ([]),
      value: ref('')
    }
  },

  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {},
      form: {},
      rules: {
        name: [{required: true, message: '名字不能为空', trigger: 'blur' }],
        username: [{required: true, message: '昵称不能为空', trigger: 'blur' }],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          {min: 6, max: 20, message: '密码长度6-20字符', trigger: 'blur'},
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur', required: true }
        ]
      },
    }
  },

  created() {
    // 获取所有班级信息，在表单中填充班级名字和昵称
    axios.get("/api/class").then(res => {
      this.classname = res.data.data
    })
    // 获取session，如果是“编辑”状态，则将session中的个人信息填充到表单中
    if (sessionStorage.getItem("3") === "edit"){
      if(sessionStorage.getItem("2") === "学生"){
        this.session1 = JSON.parse(sessionStorage.getItem("1"))
        this.finddd()
      }
    }
  },
  methods: {
    // 如果session ”1“ 为空，则说明是注册，若不为空，则说明是编辑
    ins() {
      if (sessionStorage.getItem("1") === null){
        // 插入数据库
        this.inster()
      }else {
        // 更新数据库
        this.updata()
      }
    },
    //清空
    resetForm() {
      this.ruleForm = {}
    },

    // 根据某个值查询信息并渲染上表单
    finddd() {
      this.ruleForm = this.session1
      // 删除session “3”，告诉浏览器退出编辑状态
      sessionStorage.removeItem("3")
    },
    // 更新
    updata(){
      // 以为表单中是没有id的，所以从session中获取当前用户id
      this.ruleForm.id = this.session1.id
      // 将表单信息加上id一起传回去更新数据库
      upInfo("stu",this.ruleForm).then(res => {
        switch (res.code){
          case "0":
            // 更新session
            sessionStorage.setItem("1", JSON.stringify(this.ruleForm))
            // 清空表单
            this.ruleForm = {}
            ElMessage.success("更新成功！")
            setTimeout(()=>{
              // 跳转至main页面
              this.$router.push({path:"/main"})
            },500)
            break;
          case "1":
            ElMessage.error("更新失败！")
        }
      })
    },
    // 插入注册
    inster(){
      var fname = this.ruleForm.name //记录表单接收的名字和密码
      var fpass = this.ruleForm.password
      // 判断是否已有该用户
      findUser("stu", fname, fpass).then(res => {
        if(res.code === "0"){
          ElMessage.error("该用户已存在！")
        }
        else {
          // 将新用户信息输入的注册信息插入数据库
          saveUser("stu",this.ruleForm).then(res => {
            switch (res.code){
              case "0":
                // 将新增的学生id复制给session
                this.ruleForm.id = res.data;
                // 将用户输入的信息写入session中
                sessionStorage.setItem("1", JSON.stringify(this.ruleForm))
                // 将该用户身份写入session中
                sessionStorage.setItem("2","学生")
                this.ruleForm = {}
                ElMessage.success("注册成功！")
                setTimeout(()=>{
                  // 刷新跳转至main页面
                  this.$router.push({path:"/main"})
                },500)
                break;
              case "1":
                ElMessage.error("注册失败!")
            }
          })
        }
      })
    }
  },
}
</script>

<style scoped>

.demo-ruleForm {
  width: 50%;
  margin: 0 auto;
}

</style>